<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 主体内容区域 -->
        <el-card>
            <el-row>
                <el-col>
                    <!-- 添加角色按钮 -->
                    <el-button type="primary" @click="addRoleEvent">添加角色</el-button> 
                </el-col>              
            </el-row> 
            <!-- 角色列表内容 -->
            <el-row>
                <el-table :data = "roleList" border stripe > 
                    <!-- 展开列 -->
                    <el-table-column type = "expand" >
                        <template slot-scope = "scope">
                            <el-row class="vcenter" :class="['bdbottom', i1 ===0 ? 'bdtop' : '']" v-for="(item1,i1) in scope.row.children" :key=item1.id>
                                <!-- 渲染一级权限 -->
                                <el-col :span='5' >
                                    <el-tag closable @close="removeRightsById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                 <!-- 渲染二级和三级权限 -->
                                <el-col :span='19'>
                                     <!-- 通过for循环嵌套渲染二级权限 -->
                                    <el-row class="vcenter" :class="[i2 !== 0 ? 'bdtop': '']" v-for="(item2,i2) in item1.children" :key=item2.id> 
                                         <!-- 渲染二级权限                                     -->
                                        <el-col :span="6">
                                            <el-tag closable type="success" @close="removeRightsById(scope.row,item2.id)">{{item2.authName}}                                                                                       
                                                
                                            </el-tag>
                                            <i class="el-icon-caret-right"></i>
                                        </el-col>
                                        <!-- 渲染三级权限 -->
                                        <el-col :span="18">
                                            <el-tag v-for="(item3,i3) in item2.children" :key= item3.id type="warning" closable 
                                             @close="removeRightsById(scope.row,item3.id)">
                                                {{item3.authName}}
                                              
                                            </el-tag>
                                        </el-col>
                                    </el-row>
                                </el-col>               
                            </el-row> 
                                    
                    </template> 
                    </el-table-column>                   
                    <!-- 索引列 -->
                    <el-table-column type = "index" label="#"></el-table-column>
                    <el-table-column prop="roleName" label="角色名称" ></el-table-column>
                    <el-table-column prop="roleDesc" label="角色描述" ></el-table-column>
                    <el-table-column  label="操作" width="380px">
                        <template slot-scope ="scope">
                        <el-button type="primary" icon="el-icon-edit" size = 'mini' @click="editRole(scope.row.id)" >编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size = 'mini' @click="deleteRole(scope.row.id)">删除</el-button>                        
                        <el-button type="warning" icon="el-icon-setting" size = 'mini' @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                    </el-table-column>           
                </el-table>
            </el-row>

            <!-- 点击添加按钮添加角色 -->
            <el-dialog title="添加角色" :visible.sync="addRoleVisible" 
            width="50%" >  
            <!-- 内容主体区-->
                <el-form :model="addRole" ref="addRoleRef" label-width="70px">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="addRole.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="addRole.roleDesc"></el-input>
                    </el-form-item>
                </el-form>
                <!-- 底部区域 -->
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addRoleVisible = false">取 消</el-button>
                    <el-button type="primary" @click="confirmAddRole" >确 定</el-button>
                </span>
            </el-dialog> 

            <!-- 点击编辑按钮编辑角色 -->
            <el-dialog title="编辑角色" :visible.sync="editRoleVisible" 
            width="50%" >  
            <!-- 内容主体区-->
            <el-form :model="editRoleList" ref="editRoleRef" label-width="70px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRoleList.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRoleList.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editRoleVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmEditRole" >确 定</el-button>
            </span>
            </el-dialog> 


            <!-- 点击设置权限按钮弹出对话框 -->
            <el-dialog title="分配权限" :visible.sync="setRoleRightVisible" 
            width="50%" @close = "setRightDialogClose">
            <!-- 主体内容树形控件 -->
            <el-tree :data="rightList" show-checkbox node-key="id" ref = "treeRef"
            :props="treeProps" default-expand-all :default-checked-keys="defKeys">
            </el-tree>

            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleRightVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRight">确 定</el-button>
            </span>
            </el-dialog>
        </el-card>
        
    </div>
</template>

<script>
export default {
    data(){
        return{
            //初始化获取的角色列表           
        roleList: [],
         // 添加角色对话框的显示与隐藏
        addRoleVisible: false,
        addRole:{
            roleName:'',
            roleDesc:''
        },
        // 编辑角色对话框的显示与隐藏
        editRoleVisible:false,
        editRoleList:{
            roleId:'',
            roleName:'',
            roleDesc:''
        },
        //设置权限对话框的显示与隐藏
        setRoleRightVisible:false,
        //保存获取的权限数据
        rightList:[],
        treeProps:{
            label:'authName', 
            children:'children',
        },
        //默认选中的节点的id值
        defKeys:[],
        //当前即将分配权限的id
        roleId:''

        }

    },

     created(){
        this.getRoleList()
    },

    methods:{
        async getRoleList(){
        const {data : res} = await this.$http.get('roles')
        //console.log(res)
        if(res.meta.status !== 200){
            return this.$message.error("获取角色列表失败")
        }
        this.roleList = res.data;        
        },
        //根据id删除对应的权限
       async removeRightsById(role,rightId){
        //console.log(id);
            const confirmResult =  await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', 
            {confirmButtonText: '确定', cancelButtonText: '取消',type: 'warning'
            }).catch(err => err)
            //console.log(confirmResult);
            if(confirmResult !== 'confirm'){
                return this.$message.info("已取消删除")
            }
           const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
           console.log(res);
           if(res.meta.status !==200){
               return this.$http.error("删除权限失败")
           }
           role.children = res.data
       },
        //显示添加角色对话框
       addRoleEvent(){
           this.addRoleVisible = true
       },
        //添加角色
       confirmAddRole(){
           this.$refs.addRoleRef.validate(async valid =>{
               if(!valid) return
               const {data :res} = await this.$http.post('roles',this.addRole)
               console.log(res);
               if (res.meta.status !=201){
                   this.$message.error("添加角色失败")
               }
               this.$message.success("添加角色成功")
               this.getRoleList()
               this.addRoleVisible = false
           })
       },
         //显示编辑弹框
       async editRole(id){       
            const {data : res} = await this.$http.get('roles/'+ id)
            if(res.meta.status !== 200) {
                return this.$message.error("查询角色失败")
            }
            this.editRoleList= res.data
            //console.log(res);     
           //显示编辑角色对话框
            this.editRoleVisible= true  
       },

        //根据id编辑角色   
      async confirmEditRole(){
           //console.log(this.editRoleList);
           const {data : res}= await this.$http.put('roles/' + this.editRoleList.roleId,{
               roleName:this.editRoleList.roleName,roleDesc:this.editRoleList.roleDesc
           })
            //console.log(res);
            if(res.meta.status !== 200) {
                return this.$message.error('修改失败')
            }
            this.editRoleVisible = false
            this.getRoleList()
            this.$message.success('修改成功')
            
       },
       
       
       //根据id删除角色
       async deleteRole(id){
            //console.log(id);
             const confirmResult =  await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', 
            {confirmButtonText: '确定', cancelButtonText: '取消',type: 'warning'
            }).catch(err => err)
            //如果用户确认删除，返回cancle
            //如果用户确认删除，返回confirm
            if(confirmResult !== 'confirm'){
                return this.$message.info('已取消删除')
                }
            const {data:res} = await this.$http.delete('roles/'+ id)
           // console.log(res)
           if(res.meta.status !== 200) {
               this.$message.error('删除角色失败')
           }
           this.$message.success("删除角色成功")
           this.getRoleList()
       },
    
      //展示分配权限的对话框
        async showSetRightDialog(role){
            this.roleId = role.id
            const {data : res} = await this.$http.get('rights/tree')
            console.log(res);
            if(res.meta.status !== 200){
               return this.$message.error("获取权限失败")
            }
            //获取到的权限数据保存到data中
            this.rightList = res.data
            //递归获取三级节点的id
            this.getLeafKeys(role,this.defKeys)
            this.setRoleRightVisible = true   
      },
      //通过递归的形式获取角色下所有三级权限的id，并保存到defKeys中
      getLeafKeys(node,arr){
          //如果当前节点没有children属性，则是三级权限节点
          if(!node.children){
              return arr.push(node.id)
          }
          node.children.forEach(item => 
            this.getLeafKeys(item,arr))
      },
        //监听关闭纷飞权限按钮，清空三级节点id
      setRightDialogClose(){
          this.defKeys = []
      },

      
    //   点击添加后分配角色
    async addRight(){
        const keys = [
            ...this.$refs.treeRef.getCheckedKeys(),
            ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        const idStr = keys.join(',')
        const {data :res} = await  this.$http.post(`roles/${this.roleId}/rights`,{rids : idStr})
        //console.log(res);
        if(res.meta.status!==200){
            return this.$message.error("分配权限失败")
        }
        this.$message.success("分配权限成功")
        this.getRoleList()
        this.setRoleRightVisible = false
      }
      
    }
}

</script>

<style lang="less" scoped>
.el-tag{
    margin: 7px;
}
.bdtop{
border-top: 1px solid #eee;
}
.bdbottom{
    border-bottom: 1px solid #eee;
}
.vcenter{
    display: flex;
    align-items: center;
}
</style>